package org.spring.springboot.app.file.task;


import cn.hutool.core.util.IdUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.mts20140618.AsyncClient;
import com.aliyun.sdk.service.mts20140618.models.QueryJobListRequest;
import com.aliyun.sdk.service.mts20140618.models.QueryJobListResponse;
import com.google.gson.Gson;
import com.obs.services.model.PutObjectResult;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.spring.springboot.app.base.RedisUtils;
import org.spring.springboot.app.file.dao.VideoDao;
import org.spring.springboot.app.file.domain.po.VideoPO;
import org.spring.springboot.util.DateUtils;
import org.spring.springboot.util.ObsUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Log4j2
public class CompanyVideoCroppingThread extends Thread {

    private VideoDao companyVideoDao;
    private RedisUtils redisUtils;
    private ObsUtils obsUtils;

    public CompanyVideoCroppingThread(VideoDao companyVideoDao, RedisUtils redisUtils,    ObsUtils obsUtils){
        this.companyVideoDao=companyVideoDao;
        this.redisUtils=redisUtils;
        this.obsUtils=obsUtils;
    }

    @SneakyThrows
    @Override
    public void run() {
        Example example=new Example(VideoPO.class);
        example.and().andEqualTo("isCropping",3);
        List<VideoPO> companyVideoPOList2=companyVideoDao.selectByExample(example);
        for (VideoPO companyVideoPO:companyVideoPOList2){
            if(!redisUtils.hasKey("cropping_jop"+companyVideoPO.getId())){
                redisUtils.delete("cropping_jop"+companyVideoPO.getId());
                companyVideoPO.setIsCropping(4);
                companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
                continue;
            }
            String jopId=redisUtils.get("cropping_jop"+companyVideoPO.getId())+"";
            log.info("cropping_jop::::::::::"+jopId);
            String labelDesc= video_cropping(jopId);
            log.info(":::::::::::::::::::::::::::"+labelDesc);
            if(StringUtils.isNotBlank(labelDesc)){
                if(labelDesc.equals("fail")){
                    companyVideoPO.setIsCropping(4);
                    companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
                }else{
                    companyVideoPO.setIsCropping(1);

                    InputStream inputStream = new URL(labelDesc).openStream();
//                    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
//                    parts.add("appId",companyVideoPO.getCompanyId());
//                    parts.add("file", inputStream);
//                    HttpHeaders headers = new HttpHeaders();
//                    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//                    ResponseEntity responseEntity=restTemplateUtils.post(resource_server_url,headers,parts, JSONObject.class);
//                    PutObjectResult putObjectResult = ObsUtils.uploadFile(file,relativePath, fileName);
                      String fileName=DateUtils.getDate("yyyyMMdd")+"_"+IdUtil.getSnowflakeNextIdStr()+".mp4";
                      PutObjectResult putObjectResult = obsUtils.uploadFile(inputStream,"history/"+companyVideoPO.getCompanyId(),fileName );
                      companyVideoPO.setVideoOldUrl("http://video.yujuyi.com/history/"+companyVideoPO.getCompanyId()+"/"+fileName);
                      companyVideoDao.updateByPrimaryKeySelective(companyVideoPO);
//                    filePO.setFileRealPath("http://video.yujuyi.com/history/"+companyVideoPO.getCompanyId()+"/"+fileName);

                      log.info(putObjectResult.getObjectUrl()+"::::::::::::::::"+"http://video.yujuyi.com/history/"+companyVideoPO.getCompanyId()+"/"+fileName);
                }
                redisUtils.delete("cropping_jop"+companyVideoPO.getId());
            }
        }
    }

    private static String video_cropping(String id) {
        if(StringUtils.isBlank(id)){
            return "fail";
        }
        try {
            Credential credential = Credential.builder()
                    .accessKeyId("LTAI5t7HSfSSA7R2ypyedBzB")
                    .accessKeySecret("nZQFiclFvvSH9duU6py9kyFvRlfccB")
                    .build();
            StaticCredentialProvider provider = StaticCredentialProvider.create(credential);

            AsyncClient client = AsyncClient.builder()
                    .region("cn-beijing") // Region ID
                    .credentialsProvider(provider)
                    .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("mts.cn-beijing.aliyuncs.com"))
                    .build();
            // 创建PutObjectRequest对象。
            QueryJobListRequest queryJobListRequest = QueryJobListRequest.builder()
                    .jobIds(id)
                    .build();
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // 上传字符串。
            CompletableFuture<QueryJobListResponse> response = client.queryJobList(queryJobListRequest);
            // Synchronously get the return value of the API request
            QueryJobListResponse resp = response.get();
            log.info(new Gson().toJson(resp));
            if(resp.getBody().getJobList().getJob().get(0).getState().equals("TranscodeSuccess")){
                return "https://yujuyi.oss-cn-beijing.aliyuncs.com/"+resp.getBody().getJobList().getJob().get(0).getOutput().getOutputFile().getObject();
            }
            if(resp.getBody().getJobList().getJob().get(0).getState().equals("TranscodeFail")){
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }


}
